<?php

namespace App\Http\Controllers\Api;

use App\Models\AuthRule;
use App\Utils\CodeUtil;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Artisan;
class DevelopController extends Controller
{
    function index()
    {
        //获取模块
        $module = self::find_module();
        //获取所有表
        $tables = DB::select('show tables');
        $tab = AuthRule::where("level",1)->get()->toArray();
        return view('Api/develop/index',["module"=>$module,"tables"=>$tables,"tab"=>$tab]);
    }

    /**
     * 获取系统已存在模块
     * @return array
     */
    private function find_module()
    {
        $application = dirname(dirname(dirname(__FILE__)));
        $module = scandir($application);
        $list = [];
        foreach ($module as $key => $val) {
            if (!is_dir($val)) {
                if (!strstr($val, '.')) $list[] = $val;
            }
        }
        return $list;
    }



    function makeName(Request $request)
    {
        $table = $request->input("table");
        $data = explode('_', $table);
        $name = "";
        foreach ($data as $val) {
            $name .= ucfirst($val);
        }
        echo $name;
    }

    /**
     * 保存新建的资源
     * 创建C
     * 创建M
     * 创建V
     * 创建路由 - 对应的数据
     */
    public function save(Request $request)
    {
        $controllerName = $request->input('name');  // TtDd
        $moduleName     = $request->input('module');    // Api
        $title          = $request->input('title'); // 标题名称
        $tab            = $request->input('tab'); // 标题名称
        // 生成M
        Artisan::call("make:model",["name"=>"Models/{$controllerName}"]);
        $viewName = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $controllerName));
        //生成控制器
        $controller = $this->make_controller($moduleName, $controllerName, $controllerName, $title,$viewName);
        if(!$controller) return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "控制器已经存在，换个名称试试!"]);
        //生成Validate
        //self::make_validate($moduleName, $tableName, $title);
        //生成index.html
        //驼峰样式字符串转换成下划线样式字符串（因为view下的文件命名规则是这样的）
        self::make_index($moduleName,$controllerName, $viewName, $title,"index");
        //生成create.html
        self::make_index($moduleName,$controllerName, $viewName, $title,'create');
        //生成edit.html
        self::make_index($moduleName,$controllerName, $viewName, $title,'edit');
        // 对应数据
        //生成edit.html
        self::make_data($controllerName,$tab,$title);
        // 先空
        return response()->json(['code'=> CodeUtil::SUCCESS,"msg"=> "操作成功!"]);
    }

    /**
     * 创建相关数据
     * @param $controllerName
     * @param $tab
     * @param $title
     * @return bool
     */
    private function make_data($controllerName,$tab,$title){
 //"create","save","edit","update","delete"
        $array = [
            "create"    => $title."-"."新增显示",
            "save"      => $title."-"."新增保存",
            "edit"      => $title."-"."编辑显示",
            "update"    => $title."-"."编辑保存",
            "change"    => $title."-"."状态更改",
            "delete"    => $title."-"."删除",
        ];
        $id = AuthRule::insertGetId([
            "name"      => $controllerName."_index",
            "title"     => $title,
            "type"      => 1,
            "parent_id" => $tab,
            "status"    => 1,
            'level'     => 2,
            'created_at'     => date("Y-m-d H:i:s"),
            'updated_at'     => date("Y-m-d H:i:s"),
        ]);
        foreach($array as $key => $val) {
            AuthRule::insert([
                "name"      => $controllerName."_".$key,
                "title"     => $val,
                "type"      => 1,
                "parent_id" => $id,
                'level'     => 3,
                "status"    => 1,
                'created_at'     => date("Y-m-d H:i:s"),
                'updated_at'     => date("Y-m-d H:i:s"),
            ]);
        }
        return true;

    }
    /**
     * 生成控制器
     *
     * @param $moduleName
     * @param $controllerName
     * @param $tableName
     * @param $title
     * @return bool
     */
    private function make_controller($moduleName, $controllerName, $tableName, $title,$viewName)
    {
        $application   = ((dirname(dirname(__FILE__))));
        $controllerDir = $application . '/' . $moduleName . '/';
        $controller    = $controllerDir . $controllerName . 'Controller.php';
        if (!is_dir($controllerDir)) mkdir($controllerDir, 0777, true);
        if (file_exists($controller)) {
            return false;
        }
        $template = app_path() .'/Tpl/controller.tpl';
        $content  = file_get_contents($template);
        //查找{moduleName}并替换
        $content = str_replace("{moduleName}", $moduleName, $content);
        //查找{controllerName}并替换
        $content = str_replace("{controllerName}", $controllerName, $content);
        //查找{tableName}并替换
        $content = str_replace("{tableName}", $tableName, $content);
        $content = str_replace("{view}", $viewName, $content);
        //查找{title}并替换
        $content = str_replace("{title}", $title, $content);
        file_put_contents($controller, $content);
        return true;
    }
    /**
     * 生成index.html
     *
     * @param $moduleName
     * @param $viewName
     * @param $title
     * @return bool
     */
    private function make_index($moduleName,$controllerName, $viewName, $title,$tpl)
    {
        $controllerName    = $controllerName  . 'Controller';

        $application = resource_path();
        $viewDir     = $application ."/views/". $moduleName  ."/" . $viewName;
        $validate    = $viewDir . '/' . ''.$tpl.'.blade.php';
        if (!is_dir($viewDir)) mkdir($viewDir, 0777, true);
        if (file_exists($validate)) {
            return false;
        }
        $template = app_path() .'/Tpl/'.$tpl.'.tpl';
        $content  = file_get_contents($template);
        //查找{title}并替换
        $content = str_replace("{title}", $title, $content);
        //查找{controllerName}并替换
        $content = str_replace("{controllerName}", $controllerName, $content);
        $content = str_replace("{moduleName}", $moduleName, $content);
        file_put_contents($validate, $content);
    }
}
